using System;
using System.Windows.Forms;

namespace FastNET.CleanAct.Tools.HomeTemplateEditor
{
    internal class SplashApplicationContext : ApplicationContext
    {
        #region ReadOnly Variables

        private readonly Timer _timer;
        private readonly Form _mainForm;

        #endregion

        #region CTor/DTor

        public SplashApplicationContext(Form mainForm, Form splashForm)
            : this(mainForm, splashForm, 2000)
        {
        }

        public SplashApplicationContext(Form mainForm, Form splashForm, int timeout)
            : base(splashForm)
        {
            _mainForm = mainForm;
            SplashForm = splashForm;

            if (timeout > 0)
            {
                _timer = new Timer { Interval = timeout };
                _timer.Tick += Timer_Tick;
                _timer.Start();
            }
        }

        #endregion

        #region Event Handlers

        private void Timer_Tick(Object myObject, EventArgs myEventArgs)
        {
            CloseSplashForm();
        }

        #endregion

        #region Public Properties

        public Form SplashForm { get; private set; }

        #endregion

        #region Public Functions

        public void CloseSplashForm()
        {
            if (MainForm == _mainForm)
            {
                return;
            }

            _timer.Stop();
            MainForm.Close();
        }

        #endregion

        #region Overrides

        protected override void OnMainFormClosed(object sender, EventArgs e)
        {
            if (MainForm == _mainForm)
            {
                base.OnMainFormClosed(sender, e);
            }
            else
            {
                MainForm = _mainForm;
                MainForm.Show();
            }
        }

        #endregion
    }
}
